﻿// ***********************************************************************
// Project          : Micua
// Assembly         : Micua.Utility
// Author           : iceStone
// Created          : 2014-01-05 1:20 PM
// 
// Last Modified By : iceStone
// Last Modified On : 2014-01-05 1:20 PM
// ***********************************************************************
// <copyright file="StringExtensions.cs" company="Wedn.Net">
//     Copyright (c) Wedn.Net. All rights reserved.
// </copyright>
// <summary>字符串拓展方法</summary>
// ***********************************************************************

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Micua.Utility
{
    /// <summary>
    /// 字符串拓展方法
    /// </summary>
    public static class StringExtension
    {
        #region 是否为安全SQL语句 +static bool IsSafeSql(this string str)
        /// <summary>
        /// 是否为安全SQL语句
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">指定字符串</param>
        /// <returns>真或假</returns>
        public static bool IsSafeSql(this string str)
        {
            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }
        #endregion

        #region 判断指定字符串是否为合法IP地址 +static bool IsIp(this string str)
        /// <summary>
        /// 判断指定字符串是否为合法IP地址
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">指定字符串</param>
        /// <returns>真或假</returns>
        public static bool IsIp(this string str)
        {
            return Regex.IsMatch(str, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        #endregion

        #region 判断指定字符串是否合法的日期格式 +static bool IsDateTime(this string str)
        /// <summary>
        /// 判断指定字符串是否合法的日期格式
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">指定字符串</param>
        /// <returns>真或假</returns>
        public static bool IsDateTime(this string str)
        {
            DateTime dt;
            return DateTime.TryParse(str, out dt);
        }
        #endregion

        #region 判断指定的字符串是否为数字 +static bool IsInt(this string str)
        /// <summary>
        /// 判断指定的字符串是否为数字
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">要确认的字符串</param>
        /// <returns>真或假</returns>
        public static bool IsInt(this string str)
        {
            return !string.IsNullOrEmpty(str) && Regex.IsMatch(str, "^-?\\d+$");
        }
        #endregion

        #region 判断指定的字符串是否为Url地址 +static bool IsUrl(this string str)
        /// <summary>
        /// 判断指定的字符串是否为Url地址
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">要确认的字符串</param>
        /// <returns>真或假</returns>
        public static bool IsUrl(this string str)
        {
            return Regex.IsMatch(str, "(http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?");
        }
        #endregion

        #region 判断指定的字符串是否为合法Email +static bool IsEmail(this string str)
        /// <summary>
        /// 判断指定的字符串是否为合法Email
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">指定的字符串</param>
        /// <returns>真或假</returns>
        public static bool IsEmail(this string str)
        {
            return Regex.IsMatch(str, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        #endregion




        #region 对字符串进行 HTML 编码并返回已编码的字符串 +static string HtmlEncode(this string content)
        /// <summary>
        /// 对字符串进行 HTML 编码并返回已编码的字符串
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="content">要编码的文本字符串</param>
        /// <returns>HTML 已编码的文本</returns>
        public static string HtmlEncode(this string content)
        {
            return HttpUtility.HtmlEncode(content);
        }
        #endregion

        #region 对 HTML 编码的字符串进行解码，并返回已解码的字符串 +static string HtmlDecode(this string content)
        /// <summary>
        /// 对 HTML 编码的字符串进行解码，并返回已解码的字符串
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="content">要解码的文本字符串</param>
        /// <returns>已解码的字符串</returns>
        public static string HtmlDecode(this string content)
        {
            return HttpUtility.HtmlDecode(content);
        }
        #endregion

        #region 对 URL 字符串进行编码, 返回 URL 字符串的编码结果 +static string UrlEncode(this string str, Encoding e = null)
        /// <summary>
        /// 对 URL 字符串进行编码, 返回 URL 字符串的编码结果
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">要编码的文本</param>
        /// <param name="e">编码</param>
        /// <returns>一个已编码的字符串</returns>
        public static string UrlEncode(this string str, Encoding e = null)
        {
            e = e ?? Encoding.UTF8;
            return HttpUtility.UrlEncode(str, e);
        }
        #endregion

        #region 对 URL 字符串进行解码, 返回 URL 字符串的解码结果 +static string UrlDecode(this string str, Encoding e = null)
        /// <summary>
        /// 对 URL 字符串进行解码, 返回 URL 字符串的解码结果
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">要解码的文本</param>
        /// <param name="e">编码</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(this string str, Encoding e = null)
        {
            e = e ?? Encoding.UTF8;
            return HttpUtility.UrlDecode(str);
        }
        #endregion

        #region 移除Html标记 +static string TrimHtml(this string html)
        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="html">包括HTML的源码</param>
        /// <returns>已经去除后的文字</returns>
        public static string TrimHtml(this string html)
        {
            //删除脚本和嵌入式CSS   
            html = Regex.Replace(html, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<style[^>]*?>.*?</style>", "", RegexOptions.IgnoreCase);

            //删除HTML   
            var regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
            html = regex.Replace(html, "");
            html = Regex.Replace(html, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"-->", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<!--.*", "", RegexOptions.IgnoreCase);

            html = Regex.Replace(html, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            return html.Replace("<", "").Replace(">", "").Replace("\r\n", "");
        }
        #endregion



        #region 返回字符串真实长度, 1个汉字长度为2
        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">The string.</param>
        /// <returns>System.Int32.</returns>
        public static int Length(this string str)
        {
            return string.IsNullOrEmpty(str) ? 0 : Encoding.UTF8.GetBytes(str).Length;
        }
        #endregion

        #region 截取字符串 +static string CutString(this string str, int length)
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">The string.</param>
        /// <param name="length">The length.</param>
        /// <returns>System.String.</returns>
        public static string CutString(this string str, int length)
        {
            return CutString(str, 0, length);
        }
        #endregion

        #region 截取字符串 +static string CutString(this string str, int startIndex, int length)
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:53 Created By iceStone
        /// </remarks>
        /// <param name="str">The string.</param>
        /// <param name="startIndex">The start index.</param>
        /// <param name="length">The length.</param>
        /// <returns>System.String.</returns>
        public static string CutString(this string str, int startIndex, int length)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length = length * -1;
                    if (startIndex - length < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                        startIndex = startIndex - length;
                }
                if (startIndex > str.Length)
                    return string.Empty;
            }
            else
            {
                if (length < 0)
                    return string.Empty;
                if (length + startIndex > 0)
                {
                    length = length + startIndex;
                    startIndex = 0;
                }
                else
                    return string.Empty;
            }
            if (str.Length - startIndex <= length)
            {
                length = str.Length - startIndex;
            }
            try
            {
                return str.Substring(startIndex, length);
            }
            catch
            {
                return str;
            }
        }
        #endregion

        #region 获取Gravatar头像地址 +static string GetGravatar(string email, string def, int size, char rank)
        /// <summary>
        /// 获取Gravatar头像地址
        /// </summary>
        /// <param name="email">邮箱地址</param>
        /// <param name="size">大小</param>
        /// <param name="rank">等级</param>
        /// <param name="def">缺省头像地址</param>
        /// <returns>Gravatar头像地址</returns>
        public static string Gravatar(this string email, int size = 40, char rank = 'G', string def = "")
        {
            return string.Format("http://0.gravatar.com/avatar/{0}?s={1}&d={2}&r={3}",
                email.Md5(),
                size,
                string.IsNullOrEmpty(def) ? "http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D" + size : def,
                rank);
        }
        #endregion
    }
}